package com.gardenguell.salad.helper;

import android.content.Context;
import android.os.Message;
import android.widget.Toast;
import com.gardenguell.salad.app.AppContext;
import com.gardenguell.salad.app.HandlerCenter;
import com.gardenguell.salad.util.CommonLog;
import com.gardenguell.salad.util.WifiUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by absurd on 2015/11/23.
 */
public class SimpleWifiHelper {

    private CommonLog log = CommonLog.getInstance();
    private static final int UDP_PORT = 988;

    private String mPassword = "123456";

    private String mBroadcastIp = "";
    private String mModuleName = "";
    private String mModuleIp = "";
    private String mModuleMac = "";

    private static WifiUtil mWifiUtil = WifiUtil.getInstance();


    public SimpleWifiHelper(){
        mWifiUtil = WifiUtil.getInstance();
    }

    public SimpleWifiHelper(String password){
        mWifiUtil = WifiUtil.getInstance();
        this.mPassword = password;
    }



    public String findSimpleWifi(){
        mBroadcastIp = mWifiUtil.getBroadcastIp();
        UdpClientSocket client = null;
        String res = "";
        try {
            client = new UdpClientSocket();
            client.send(mBroadcastIp, UDP_PORT, (mPassword + "AT+LKSTT\n").getBytes());
            String info = client.receive(UdpClientSocket.SOCKET_TIME_OUT_SHORT);
            showToast("当前网络广播IP" + mBroadcastIp +
                    "    在当前网络中搜索wifi模块,请求返回 : " + info);
            if(checkRes(info)){
               String s[] = info.split("=");
                if(s != null && s.length == 2){
                    String ss[] = s[1].split(",");
                    if(ss[0].equals("1")) {
                        res = ss[1].substring(1, ss[1].length() -1 );
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast(e.getMessage());
        }finally {
            if(client != null){
                client.close();
            }
        }
        mModuleIp = res;
        return res;
    }

    public String getModuleIp(){
        return mModuleIp;
    }

    public String findModuleName(){
        if(mModuleIp == null || mModuleIp.isEmpty())
            return "";
        UdpClientSocket client = null;
        String res = "";
        try {
            client = new UdpClientSocket();
            client.send(mModuleIp, UDP_PORT, (mPassword + "AT+SSID=?\n").getBytes());
            String info = client.receive(UdpClientSocket.SOCKET_TIME_OUT_SHORT);
            showToast("当前网络广播IP" + mBroadcastIp +
                    "    在当前网络中搜索wifi模块名称,请求返回 : " + info);
            if(checkRes(info)){
                String s[] = info.split("=");
                if(s != null && s.length == 2){
                    res = s[1].substring(1, s[1].length() - 2);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast(e.getMessage());
        }finally {
            if(client != null){
                client.close();
            }
        }
        mModuleName = res;
        return res;
    }

    public String getModuleName(){
        return mModuleName;
    }

    private boolean sendCommand(UdpClientSocket client, String ip, int port, String command) throws IOException {
        client.send(ip, port, (mPassword + command).getBytes());
        String info = client.receive(UdpClientSocket.SOCKET_TIME_OUT_LONG);
        return checkRes(info);
    }

    public boolean configureModule(String ssid, String password){
        if(mModuleIp == null || mModuleIp.isEmpty())
            return false;
        UdpClientSocket client = null;
        boolean res = false;
        try {
            client = new UdpClientSocket();
            if(sendCommand(client, mModuleIp, UDP_PORT, "AT+WPRT=!0\n")){
                log.d("set the wifi mode ok");
                if(sendCommand(client, mModuleIp, UDP_PORT, "AT+SSID=!"+ssid+"\n")){
                    log.d("set the ssid ok");
                    if(sendCommand(client, mModuleIp, UDP_PORT, "AT+ENCRY=!7\n")){
                        log.d("set the wifi encry mode ok");
                        if(sendCommand(client, mModuleIp, UDP_PORT, "AT+KEY=!1,0,"+password+"\n")){
                            log.d("set the password ok");
                            if(sendCommand(client, mModuleIp, UDP_PORT, "AT+NIP=0\n")){
                                log.d("set the wifi ip ok");
                                if(sendCommand(client, mModuleIp, UDP_PORT, "AT+PMTF\n")){
                                    log.d("set the configuration to flash ok");
                                    if(sendCommand(client, mModuleIp, UDP_PORT, "AT+Z\n")){
                                        log.d("reboot the module ok");
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(client != null){
                client.close();
            }
        }
        return res;
    }

    public boolean configureServerInfo(String ip, int remotePort, int localPort){
        if(mModuleIp == null || mModuleIp.isEmpty())
            return false;
        UdpClientSocket client = null;
        boolean res = false;
        try {
            client = new UdpClientSocket();
            String cmd = "AT+ATRM=!0,0," + ip + "," + remotePort + "," + localPort +  "\n";
            return sendCommand(client, mModuleIp, UDP_PORT, cmd);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(client != null){
                client.close();
            }
        }
        return res;
    }

    public String findModuleMac(){
        if(mModuleIp == null || mModuleIp.isEmpty())
            return "";
        UdpClientSocket client = null;
        String res = "";
        try {
            client = new UdpClientSocket();
            client.send(mModuleIp, UDP_PORT, (mPassword + "AT+QMAC\n").getBytes());
            String info = client.receive(UdpClientSocket.SOCKET_TIME_OUT_SHORT);
            if(checkRes(info)){
                String s[] = info.split("=");
                if(s != null && s.length == 2){
                    res = s[1].substring(0, s[1].length() - 3);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(client != null){
                client.close();
            }
        }
        mModuleMac = res;
        return res;
    }

    public String getModuleMac(){
        return mModuleMac;
    }





    private boolean checkRes(String res){
        if(res == null || res.isEmpty())
            return false;
        if(res.startsWith("+OK"))
            return true;
        return false;
    }



    private void showToast(String s){
        Message msg  = Message.obtain();
        msg.what = HandlerCenter.Message.SHOW_TOAST;
        msg.obj = s;
        HandlerCenter.getInstance().getHandler(HandlerCenter.Flag.BASE_ACTIVITY)
                .sendMessage(msg);
    }
}
